package com.opencursor;

import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.ui.FormBuilder;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;

public class CursorSettingsConfigurable implements Configurable {
    private JPanel myMainPanel;
    private TextFieldWithBrowseButton myCursorPathField;

    @Nls(capitalization = Nls.Capitalization.Title)
    @Override
    public String getDisplayName() {
        return "Cursor Settings";
    }

    @Override
    public JComponent getPreferredFocusedComponent() {
        return myCursorPathField.getTextField();
    }

    @Nullable
    @Override
    public JComponent createComponent() {
        myCursorPathField = new TextFieldWithBrowseButton();

        FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false, false)
                .withTitle("Select Cursor Executable")
                .withDescription("Choose the Cursor editor executable")
                .withFileFilter(file -> file.getExtension() != null && file.getExtension().equals("exe"));

        myCursorPathField.addBrowseFolderListener(
                "Select Cursor Executable",
                "Choose the Cursor editor executable",
                null,
                descriptor);

        myMainPanel = FormBuilder.createFormBuilder()
                .addLabeledComponent(new JBLabel("Cursor Path: "), myCursorPathField)
                .addComponentFillVertically(new JPanel(), 0)
                .getPanel();

        return myMainPanel;
    }

    @Override
    public boolean isModified() {
        CursorSettings settings = CursorSettings.getInstance();
        return !myCursorPathField.getText().equals(settings.getCursorPath());
    }

    @Override
    public void apply() throws ConfigurationException {
        CursorSettings settings = CursorSettings.getInstance();
        settings.setCursorPath(myCursorPathField.getText());
    }

    @Override
    public void reset() {
        CursorSettings settings = CursorSettings.getInstance();
        myCursorPathField.setText(settings.getCursorPath());
    }

    @Override
    public void disposeUIResources() {
        myMainPanel = null;
    }
}